package com.icesoft.core.web.suppose.setting.service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.InitializingBean;

import com.icesoft.core.web.helper.PathUtil;
import com.icesoft.core.web.model.SysSettingDTO;
import com.icesoft.core.common.util.JsonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class SysSettingFileServiceImpl implements ISysSettingService, InitializingBean {

	private Map<String, List<SysSettingDTO>> settingMap;

	@Override
	public Map<String, String> findByGroup(String groupName) {
		Map<String, String> objectMap = new HashMap<>();
		List<SysSettingDTO> list = settingMap.get(groupName);
		if (list != null) {
			list.forEach(dto -> {
				objectMap.put(dto.getKeyName(), dto.getVal());
			});
		}
		return objectMap;
	}

	static final String settingFilePath = PathUtil.getProjectRootPath() + "setting.json";
	ObjectMapper mapper = new ObjectMapper();

	@Override
	public synchronized void createSettings(Collection<SysSettingDTO> sysSetting) {
		sysSetting.forEach(dto -> {
			List<SysSettingDTO> list = settingMap.getOrDefault(dto.getGroupName(), new ArrayList<>());
			list.add(dto);
			settingMap.put(dto.getGroupName(), list);
		});
		save();

	}

	private void save() {
		try {
			FileUtils.writeStringToFile(new File(settingFilePath),
					mapper.writerWithDefaultPrettyPrinter().writeValueAsString(settingMap));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		File file = new File(settingFilePath);
		if (file.exists()) {
			try {
				String json = FileUtils.readFileToString(file);
				settingMap = JsonUtil.toObject(json,
						new TypeReference<ConcurrentHashMap<String, List<SysSettingDTO>>>() {
						});
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (settingMap == null) {
				throw new RuntimeException(settingFilePath + "文件读取错误");
			}
		} else {
			settingMap = new ConcurrentHashMap<>();
		}

	}

	@Override
	public void remove(String groupName, String keyName) {
		List<SysSettingDTO> list = settingMap.get(groupName);
		for (Iterator<SysSettingDTO> iterator = list.iterator(); iterator.hasNext();) {
			SysSettingDTO sysSettingDTO = iterator.next();
			if (sysSettingDTO.getKeyName().equals(keyName)) {
				iterator.remove();
				break;
			}
		}
		save();
	}

}
